package org.example.user.manage.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.commons.config.MiniProgramUserProperties;
import org.example.commons.constant.HttpStatusConstant;
import org.example.commons.controller.BaseController;
import org.example.commons.entity.SysAdmin;
import org.example.commons.entity.SysUser;
import org.example.commons.utils.SortUtils;
import org.example.commons.utils.WeiXinUtils;
import org.example.commons.vo.ResultVO;
import org.example.user.manage.form.SysUserForm;
import org.example.user.manage.form.SysUserSearchForm;
import org.example.user.manage.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author bothin
 */
@RestController
@RequestMapping("/api/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MiniProgramUserProperties userProperties;

    /**
     * 导出excel
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export/excel")
    public void exportExcel(@RequestParam(name = "ids", required = false) Long[] ids,
                            HttpServletResponse response) throws IOException {
        List<SysUser> data = null;
        if (ids == null || ids.length == 0) {
            data = sysUserService.queryAll();
        } else {
            data = sysUserService.findByUserIdIn(ids);
        }
        super.exportExcel(response, data, SysUser.class, "住户数据表");
    }

    @GetMapping("/{id}")
    public ResultVO findOne(@PathVariable("id") Long id) {
        return ResultVO.success(sysUserService.queryById(id));
    }

    @GetMapping("/openid")
    public ResultVO findByOpenid(@RequestParam("openid") String openid) {
        return ResultVO.success(sysUserService.findByOpenid(openid));
    }

    /**
     * 用于注册登录
     *
     * @param phone 住户电话
     * @return ResultVO
     */
    @GetMapping("/phone")
    public ResultVO findByPhone(@RequestParam("phone") String phone) {
        return ResultVO.success(sysUserService.findByPhone(phone));
    }

    /**
     * 判断该电话是否改换给住户（住户修改电话）
     * true 可以被修改
     *
     * @param phone 住户电话
     * @return ResultVO
     */
    @GetMapping("/phone/judge")
    public ResultVO judgePhone(@RequestParam("phone") String phone, @RequestParam("userId") Long userId) {
        SysUser userByPhone = sysUserService.findByPhone(phone);
        if (Objects.isNull(userByPhone))        //该电话尚未被人注册
            return ResultVO.success(true);
        else if (userByPhone.getUserId().equals(userId))  //该电话为他本人拥有
            return ResultVO.success(true);
        return ResultVO.success(false);
    }

    /**
     * 查询住户列表
     *
     * @param page  页数
     * @param size  每页大小
     * @param isAsc 是否正序排序
     * @param field 排序的字段
     * @return ResultVO
     */
    @GetMapping
    public ResultVO findList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                             @RequestParam(name = "size", defaultValue = "10") Integer size,
                             @RequestParam(name = "isAsc", defaultValue = "true") Boolean isAsc,
                             @RequestParam(name = "field", defaultValue = "userId") String field) {
        //排序
        Sort sort = SortUtils.getSort(isAsc, field);
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        Page<SysUser> users = sysUserService.queryAllPage(pageRequest);
        return ResultVO.success(users);
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public ResultVO findAll() {
        return ResultVO.success(sysUserService.queryAll());
    }

    /**
     * 条件查询住户列表
     *
     * @return ResultVO
     */
    @GetMapping("/search")
    public ResultVO SearchList(SysUserSearchForm userSearchForm) {
        PageRequest pageRequest = null;
        if (StringUtils.isEmpty(userSearchForm.getField())) {
            pageRequest = PageRequest.of(userSearchForm.getPage() - 1, userSearchForm.getSize());
        } else {
            //排序
            Sort sort = userSearchForm.getIsAsc() ? Sort.by(userSearchForm.getField()).ascending() :
                    Sort.by(userSearchForm.getField()).descending();
            pageRequest = PageRequest.of(userSearchForm.getPage() - 1, userSearchForm.getSize(), sort);
        }
        Page<SysUser> users = sysUserService.searchList(userSearchForm, pageRequest);
        return ResultVO.success(users);
    }

    /**
     * 保存用户
     *
     * @param userForm 住户表单对象
     * @return ResultVO
     */
    @PostMapping
    public ResultVO saveSysUser(@RequestBody SysUserForm userForm) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userForm, user);
        return ResultVO.success(sysUserService.insert(user));
    }

    /**
     * 更新用户
     *
     * @param userForm 住户表单对象
     * @return ResultVO
     */
    @PutMapping
    public ResultVO updateSysUser(@RequestBody SysUserForm userForm) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userForm, user);
        return ResultVO.success(sysUserService.update(user));
    }

    @PutMapping("/bind/openid")
    @Transactional
    public ResultVO bindOpenid(@RequestParam(name = "userId") Long userId, @RequestParam(name = "code") String code) throws JsonProcessingException {

        String openid = WeiXinUtils.getRealOpenid(code, userProperties.getAppId(), userProperties.getAppSecret());
        SysUser userOrigin = sysUserService.findByOpenid(openid);
        //解绑原来的账号
        if (userOrigin != null) {
            userOrigin.setOpenid("");
            sysUserService.update(userOrigin);
        }
        //更新
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setOpenid(openid);
        sysUserService.update(user);


        return ResultVO.success("绑定当前账号成功！");
    }

    @DeleteMapping
    public ResultVO deleteSysUser(@RequestParam("id") Long id) {
        sysUserService.deleteById(id);
        return ResultVO.success();
    }

    @DeleteMapping("/list")
    @Transactional
    public ResultVO deleteSysUserList(@RequestParam("ids") Long[] ids) {
        for (Long id : ids) {
            sysUserService.deleteById(id);
        }
        return ResultVO.success();
    }

    @GetMapping("/password")
    public ResultVO getPassword(@RequestParam("id") Long id) {
        String password = sysUserService.getPassword(id);
        ResultVO resultVO = ResultVO.success();
        resultVO.put("password", password);
        return resultVO;
    }

    /**
     * 修改密码
     *
     * @param id
     * @param oldPassword
     * @param password
     * @return
     */
    @PostMapping("/password")
    public ResultVO setPassword(@RequestParam("id") Long id,
                                @RequestParam("oldPassword") String oldPassword,
                                @RequestParam("password") String password) {
        String originPassword = sysUserService.getPassword(id);
        if (originPassword != null && oldPassword != null && oldPassword.equals(originPassword)) {
            sysUserService.setPassword(id, password);
            return ResultVO.success();
        }

        return ResultVO.error("修改密码错误！或许原密码不正确");

    }

    /**
     * 重置密码
     *
     * @param id
     * @param password
     * @return
     */
    @PutMapping("/password")
    public ResultVO restPassword(@RequestParam("id") Long id,
                                 @RequestParam("password") String password) {
        sysUserService.setPassword(id, password);
        return ResultVO.success();

    }

}
